package com.xdf.mcsecurity.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserService myUserService;

    @Override
    public void configure(WebSecurity web) throws Exception {
//        super.configure(web);通过IDEA重写方法自带来的
        // 忽略静态资源的权限验证，这里不可放入登录请求，否则导致认证成功后不写入缓存，后续请求都没有权限
        web.ignoring().antMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.authorizeRequests().antMatchers("/").permitAll() //项目主路径无权限可访问
                .anyRequest().authenticated()// 其他请求都要求权限
                .and().logout().permitAll() //注销请求，无权限可访问
                .and().formLogin();// 使用表单登录（不兼容前后分离：Angular）
        http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        // 创建内存用户（不使用数据库存储账号信息），依次是：用户名、密码、角色
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).
                withUser("admin").password(new BCryptPasswordEncoder().encode("xdf123")).roles("ADMIN");
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).
                withUser("1001").password(new BCryptPasswordEncoder().encode("xdf1001")).roles("ADMIN");
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).
                withUser("1002").password(new BCryptPasswordEncoder().encode("xdf1002")).roles("ADMIN");
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).
                withUser("1004").password(new BCryptPasswordEncoder().encode("xdf1004")).roles("USER");

        // 使用自定义用户服务要注释掉上面的代码，同时指定密码加密工具
        //auth.userDetailsService(myUserService).passwordEncoder(new MyPasswordEncoder());
    }
}
